package beanstao.util.store.database.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.Node;

import beanstao.util.log.LogHelper;

public class MysqlVerify extends AbstractDbVerify
{
	private static final String BASE_DB = "mysql";
	private static final String LOG_DB = "com_beanstao_ecms100_log";

	@Override
	public boolean verify(Element element)
	{
		System.out.println("...ecms >>> 读取Mysql数据库配置。开始验证数据库完整性。");
		Connection conn_0 = null;
		Statement st = null;
		boolean isconn = false;
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (ClassNotFoundException e)
		{
			System.err.println("Mysql校验时数据库驱动未载入。" + e);
			return false;
		}

		String name = "";
		String value = "";
		String connString = ((Element) element.selectSingleNode("conns")).getTextTrim();

		for (Node node : (Element) element.selectSingleNode("main_guest_names"))
		{
			if (!(node instanceof Element))
				continue;
			Element subElement = (Element) node;
			name = subElement.attributeValue("name");
			value = subElement.attributeValue("value");
			try
			{
				conn_0 = DriverManager.getConnection(String.format(connString, BASE_DB), name, value);
				isconn = true;
				break;
			}
			catch (SQLException e)
			{
				continue;
			}
		}

		if (!isconn)
		{
			System.err.println("Mysql校验时数据库无法连接。");
			return false;
		}
		String ecmsnameString = element.selectSingleNode("username").getText();
		String ecmspwString = element.selectSingleNode("credentials").getText();
		try
		{
			st = conn_0.createStatement();
			st.executeQuery("grant select,insert,update,delete,create,alter,drop on *.* to " + ecmsnameString + "@\"%\" Identified by \"" + ecmspwString + "\";");
		}
		catch (SQLException e1)
		{
			System.err.println("数据库用户创建失败。");
			return false;
		}

		Element dbsElement = (Element) element.selectSingleNode("dbs");
		List<? extends Node> dbs = dbsElement.selectNodes("database");
		ArrayList<String> databasesList = new ArrayList<String>();
		for (Node node : dbs)
			if (node instanceof Element)
			{
				Element ss = (Element) node;
				String dbnameString = ss.attributeValue("name");
				databasesList.add(dbnameString);
			}

		for (int i = 0; i < databasesList.size(); i++)
		{
			// 创建数据库
			String db = databasesList.get(i);
			try
			{
				try
				{
					st = this.createLogDb(element, st, ecmsnameString, ecmspwString, connString, db);
				}
				catch (Exception e)
				{
					// 当异常时，一般是没有数据库，先建库
					st = conn_0.createStatement();
					st.executeUpdate("create database " + db);
					System.out.println("...ecms >>> DbHelper" + "创建数据库" + db + "成功...");
					st = this.createLogDb(element, st, ecmsnameString, ecmspwString, connString, db);
				}
			}
			catch (Exception e)
			{
				try
				{
					conn_0.close();
					st.close();
				}
				catch (SQLException e1)
				{
					LogHelper.logInfo(e1, "MysqlVerify" + "无法关闭连接对象，可能对系统产生影响。");
				}
			}
		}
		System.out.println("...ecms >>> 验证Mysql数据库完整性结束。");
		return true;
	}

	private Statement createLogDb(Element element, Statement st, String name, String value, String connString, String db) throws SQLException
	{
		DriverManager.getConnection(String.format(connString, db), name, value);
		System.out.println("...ecms >>> 验证" + db + "数据库正常。");
		if (db.equals("com_pan_ecms100_log"))
		{
			Connection conn_log = DriverManager.getConnection(String.format(connString, LOG_DB), name, value);
			st = conn_log.createStatement();
			String logsqlString = element.selectSingleNode("log4j").getText().trim();
			st.executeUpdate(logsqlString);
			System.out.println("...ecms >>> 日志数据库-log4j表创建成功。");
			conn_log.close();
		}
		return st;
	}
}
